import ContactDrawer from '@/components/ContactDrawer';
import Footer from '@/components/Footer';
import WeChatDrawer from '@/components/WeChatDrawer';
import { loginAppForPhone, loginAppForWechatAuthorize } from '@/services/api/api-login';
import { isDev } from '@/utils/dev';
import { setToken } from '@/utils/token';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { DrawerForm } from '@ant-design/pro-components';
import { LoginForm, ProFormText } from '@ant-design/pro-form';
import { Alert, Divider, message, Spin, Tabs, Typography, Image } from 'antd';
import React, { useEffect, useState } from 'react';
import { flushSync } from 'react-dom';
import { Helmet, history, useModel } from 'umi';

type LoginParams = {
  phone?: string;
  password?: string;
  autoLogin?: boolean;
  type?: string;
};

const Login: React.FC = () => {
  const [type, setType] = useState<string>('wechat');
  const { initialState, setInitialState } = useModel('@@initialState');
  const [weChatUrl, setWeChatUrlState] = useState<string>();
  useEffect(() => {
    loginAppForWechatAuthorize({ serviceName: 'xtbs' }).then(({ code, data }) => {
      if (code === 0) {
        setWeChatUrlState(data);
      }
    });
  }, []);

  const handleSubmit = async (values: LoginParams) => {
    // 登录
    const response = await loginAppForPhone({ ...values, type, serviceName: 'xtbs' });
    if (response.code === 0) {
      const { state, satoken, accountId } = response.data;

      setToken(satoken);

      if (state === 5) {
        //选择登录
        history.push('/user/select?accountId=' + accountId);
      } else {
        if (!history) return;
        const userInfo = await initialState?.fetchUserInfo?.();
        if (userInfo) {
          message.success('登录成功！');
          history.push('/');
          flushSync(() => {
            setInitialState((s) => ({
              ...s,
              currentUser: userInfo,
            }));
          });
        }
        return;
      }
    }
  };

  return (
    <div
      style={{
        display: 'flex',
        flexDirection: 'column',
        height: '100vh',
        overflow: 'auto',
        backgroundImage:
          "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
        // backgroundImage: '/page_login_layout_bg_img_4.png',
        backgroundSize: '100% 100%',
      }}
    >
      <Helmet>
        <title>登录页 - 五媒协同</title>
      </Helmet>
      <div
        style={{
          flex: '1',
          padding: '32px 0',
        }}
      >
        <div
          style={{
            alignContent: 'center',
            display: 'flex',
            justifyContent: 'center',
          }}
        >
          <img alt="logo" width={150} height={150} src="/logo.png" />
        </div>
        <LoginForm
          contentStyle={{
            minWidth: 400,
            maxWidth: '75vw',
            marginTop: '-10px',
          }}
          title={<span style={{ color: '#5E5C5D' }}>五媒协同</span>}
          subTitle=" "
          // initialValues={{
          //   autoLogin: true,
          // }}
          submitter={
            type === 'phone' && {
              searchConfig: {
                submitText: '登录',
              },
              submitButtonProps: {
                size: 'large',
                style: {
                  width: '100%',
                },
              },
            }
          }
          onFinish={async (values) => {
            await handleSubmit(values as LoginParams);
          }}
        >
          <Tabs
            activeKey={type}
            onChange={setType}
            centered
            items={[
              {
                key: 'wechat',
                label: '微信登录',
              },
              {
                key: 'wxamp',
                label: '微信小程序',
              },
              isDev() && {
                key: 'phone',
                label: '手机号密码登录',
              },
            ]}
          />
          {type === 'wechat' && (
            <div
              style={{ paddingTop: 20, overflow: 'auto', textAlign: 'center', minHeight: '400px' }}
            >
              <Spin spinning={!weChatUrl}>
                <iframe
                  // sandbox="allow-scripts allow-same-origin allow-top-navigation"
                  src={weChatUrl}
                  height="404"
                  frameBorder="0"
                  scrolling="false"
                />
              </Spin>
              {/* {weChatUrl ? <iframe src={weChatUrl} height="404" frameBorder="0" scrolling="false" /> : <Spin />} */}
            </div>
          )}
          {type === 'wxamp' && (
            <div style={{ paddingTop: 20, overflow: 'auto', textAlign: 'center' }}>
              <img
                src="/qr/qr-wxamp-xtbs.png"
                style={{
                  padding: 25,
                  width: '100%',
                  height: '100%',
                  objectFit: 'cover',
                }}
              />
            </div>
          )}
          {isDev() && type === 'phone' && (
            <div>
              <ProFormText
                name="phone"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined />,
                }}
                placeholder={'手机号'}
                rules={[
                  {
                    required: true,
                    message: '请输入手机号',
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                placeholder={'密码'}
                rules={[
                  {
                    required: true,
                    message: '请输入密码！',
                  },
                ]}
              />
            </div>
          )}
          <Alert
            type="error"
            message={
              <>
                现新闻选题管理平台以迁移到五媒协同
                <a href="https://moc.ljsyy.net/guangda.html" style={{
                  paddingLeft: '15px',
                }}>点击进入</a>
              </>
            } />
          <Alert
            style={{
              marginTop: '25px',
            }}
            message={
              <>
                扫码成功后，没有成功进入系统
                <DrawerForm
                  key="weChat_drawer"
                  title="使用Chrome或Edge浏览器"
                  trigger={<a
                    style={{
                      paddingLeft: '15px',
                    }}
                  >
                    点击查看如何解决
                  </a>}
                  autoFocusFirstInput
                  drawerProps={{
                    size: 'large',
                    forceRender: true,
                    destroyOnClose: true,
                    width: '600px',
                  }}
                  submitter={false}
                >
                  <Typography.Title level={3}>
                    方法一、扫码后浏览器上方出现阻止重定向的提示，点击提示，选择始终允许弹出窗口并从https://xtbs.ljsyy.net重定向。
                  </Typography.Title>
                  <Image src="https://xtbs.ljsyy.net/resources/redirect/redirect-1.png" />
                </DrawerForm>
              </>
            }
            type="error"
          />
          <Alert
            style={{
              marginTop: '25px',
            }}
            message={
              <>
                注意，请使用Chrome或Edge浏览器，不推荐使用微信内置浏览器
                <WeChatDrawer
                  trigger={
                    <a
                      style={{
                        paddingLeft: '15px',
                      }}
                    >
                      点击操作方式
                    </a>
                  }
                />
              </>
            }
            type="warning"
          />
          <Alert
            style={{
              marginTop: '25px',
              marginBottom: '15px'
            }}
            message={
              <>
                如碰到问题可联系管理员进行咨询
                <ContactDrawer />
              </>
            }
            type="warning"
          />
        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};

export default Login;
